/**
 * 本函数可用于初始化一套 RBAC 必要的数据，通常不需要删除此云函数，也不要开启 HTTP 调用。
 */
import cloud from "@lafjs/cloud";
import * as assert from "assert";
const db = cloud.database();
import { hashPassword } from "@/utils";

export async function main() {
  //创建菜单
  await createMenu();
  //创建部门
  await createDept();
  //创建角色
  await createRole();

  // 创建初始管理员
  await createFirstAdmin("admin", "admin123");
  return "ok";
}

// 创建初始管理员
async function createFirstAdmin(username: string, password: string) {
  const collection = "admin-staff";
  await createDb(collection, "username");
  const { total } = await db.collection(collection).count();
  if (total > 0) {
    console.log("admin already exists");
    return;
  }
  try {
    const { total } = await db.collection(collection).count();
    if (total > 0) {
      console.log("admin already exists");
      return;
    }
    const items = {
      username: username,
      avatar: "https://laf.run/logo.png",
      name: "Admin",
      roleList: [],
      created_at: Date.now(),
      updated_at: Date.now()
    };
    const { data } = await db.collection("admin-role").get();
    const roles = data.map(it => it._id);
    items.roleList = roles;
    const r_add = await db.collection(collection).add(items);
    assert.ok(r_add.id, "add admin occurs error");
    await db.collection("password").add({
      uid: r_add.id,
      password: hashPassword(password),
      type: "login",
      status: "active",
      created_at: Date.now(),
      updated_at: Date.now()
    });
    return r_add.id;
  } catch (error) {
    console.error(error.message);
  }
}

// 创建初始角色
async function createRole() {
  const collection = "admin-role";
  const { total } = await db.collection(collection).count();
  if (total > 0) {
    console.log("admin already exists");
    return;
  }
  const role = {
    name: "superadmin",
    label: "超级管理员",
    description: "系统初始化的超级管理员",
    deptList: [], //部门
    key: "superadmin",
    menuList: [], //菜单
    status: true
  };
  await createDb(collection);
  const { data: deptList } = await db
    .collection("admin-dept")
    .field({ _id: 1 })
    .get();
  const { data: menuList } = await db
    .collection("admin-menu")
    .field({ _id: 1 })
    .get();
  role.deptList = deptList.map(res => res._id);
  role.menuList = menuList.map(res => res._id);
  const result = await db.collection(collection).add({
    ...role,
    created_at: Date.now(),
    updated_at: Date.now()
  });
  assert.ok(result.id, "add admin occurs error");
}

// 创建部门

async function createDept() {
  const collection = "admin-dept";
  const { total } = await db.collection(collection).count();
  if (total > 0) {
    console.log("admin already exists");
    return;
  }
  const PresetData = [
    {
      name: "lafPureAdmin",
      sort: "0",
      status: 0,
      children: [
        {
          name: "研发部",
          sort: "0",
          status: 0,
          children: []
        }
      ]
    }
  ];
  await createDb(collection);
  for (let index = 0; index < PresetData.length; index++) {
    const element = PresetData[index];
    await insertTreeData(collection, element, "0", "parentDeptId");
  }
}
// 判断数据库是否存在 不存在就创建

async function createDb(collection, index = "") {
  const { total } = await db.collection(collection).count();
  if (total > 0) {
    console.log("admin already exists");
    return;
  }
  if (index) {
    await cloud.mongo.db
      .collection(collection)
      .createIndex(index, { unique: true });
    console.log("创建表成功带索引");
  } else {
    await cloud.mongo.db.collection(collection);
    console.log("创建表成功不带索引");
  }
}
//树结构的方式插入数据
async function insertTreeData(
  collection,
  node,
  parentId,
  parentName = "parentName"
) {
  const item = { ...node };
  item[parentName] = parentId;
  delete item.children;
  const result = await db.collection(collection).add({
    ...item,
    created_at: Date.now(),
    updated_at: Date.now()
  });
  // 递归插入子节点
  for (const child of node.children) {
    await insertTreeData(collection, child, result.id, parentName);
  }
}

//创建菜单
async function createMenu() {
  const collection = "admin-menu";
  const { total } = await db.collection(collection).count();
  if (total > 0) {
    console.log("admin already exists");
    return;
  }
  const PresetData = [
    {
      name: "系统管理",
      type: "M",
      perms: "sys",
      path: "/systemMnagement",
      isFrame: false,
      isCache: true,
      sort: 0,
      status: true,
      visible: true,
      component: "",
      query: "",
      remark: "",
      createTime: "",
      editTime: "",
      children: [
        {
          name: "菜单管理",
          type: "C",
          perms: "oms:menu",
          path: "/oms/menu",
          isFrame: false,
          isCache: true,
          sort: 0,
          status: true,
          visible: true,
          component: "/oms/menu",
          query: "",
          remark: "",
          createTime: "",
          editTime: "",
          children: [
            {
              name: "新增",
              type: "F",
              perms: "oms:menu:add",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            },
            {
              name: "详情",
              type: "F",
              perms: "oms:menu:detail",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            },
            {
              name: "更新",
              type: "F",
              perms: "oms:menu:update",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            },
            {
              name: "删除",
              type: "F",
              perms: "oms:menu:remove",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            }
          ]
        },
        {
          name: "用户管理",
          type: "C",
          perms: "oms:staff",
          path: "/oms/staff",
          isFrame: false,
          isCache: true,
          sort: 0,
          status: true,
          visible: true,
          component: "/oms/staff",
          query: "",
          remark: "",
          createTime: "",
          editTime: "",
          children: [
            {
              name: "新增",
              type: "F",
              perms: "oms:staff:add",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            },
            {
              name: "编辑",
              type: "F",
              perms: "oms:staff:update",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            },
            {
              name: "删除",
              type: "F",
              perms: "oms:staff:remove",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            },
            {
              name: "详情",
              type: "F",
              perms: "oms:staff:detail",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            }
          ]
        },
        {
          name: "角色管理",
          type: "C",
          perms: "oms:role",
          path: "/oms/role",
          isFrame: false,
          isCache: true,
          sort: 0,
          status: true,
          visible: true,
          component: "/oms/role",
          query: "",
          remark: "",
          createTime: "",
          editTime: "",
          children: [
            {
              name: "新增",
              type: "F",
              perms: "oms:role:add",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            },
            {
              name: "更新",
              type: "F",
              perms: "oms:role:update",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            },
            {
              name: "详情",
              type: "F",
              perms: "oms:role:detail",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            },
            {
              name: "删除",
              type: "F",
              perms: "oms:role:remove",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            }
          ]
        },
        {
          name: "部门管理",
          type: "C",
          perms: "oms:dept",
          path: "/oms/dept",
          isFrame: false,
          isCache: true,
          sort: 0,
          status: true,
          visible: true,
          component: "/oms/dept",
          query: "",
          remark: "",
          createTime: "",
          editTime: "",
          children: [
            {
              name: "新增",
              type: "F",
              perms: "oms:dept:add",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            },
            {
              name: "更新",
              type: "F",
              perms: "oms:dept:update",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            },
            {
              name: "删除",
              type: "F",
              perms: "oms:dept:remove",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            },
            {
              name: "详情",
              type: "F",
              perms: "oms:dept:detail",
              path: "menu",
              isFrame: false,
              isCache: false,
              sort: 0,
              status: true,
              visible: true,
              component: "",
              query: "",
              remark: "",
              createTime: "",
              editTime: "",
              children: []
            }
          ]
        }
      ]
    }
  ];
  await createDb(collection);
  for (let index = 0; index < PresetData.length; index++) {
    const element = PresetData[index];
    await insertTreeData(collection, element, "0", "parentMenuId");
  }
}
